package cn.zooz.admin.controller;

import cn.zooz.common.util.kit.PasswordUtil;
import cn.zooz.entity.SysUser;
import cn.zooz.service.o.dto.UserDto;
import cn.zooz.service.sys.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.StoppedSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;

/**
 * Created by Bradish7Y on 2017/9/25.
 */
@Controller
@Slf4j
public class LoginController {
    @Resource
    private SysLoginService sysLoginService;

    @GetMapping(value = "/reg")
    public String reg(){
        return "user/reg";
    }

    /**
     * 注册
     *
     * @param userDto
     * @return
     */
    @PostMapping(value = "/reg", produces = "application/json")
    @ResponseBody
    public Boolean reg(@ModelAttribute UserDto userDto) {

        SysUser user = new SysUser();
        //复制bean
        BeanUtils.copyProperties(userDto, user);
        String salt = System.currentTimeMillis() + "";

        user.setPassword(PasswordUtil.generatePassword("md5", user.getPassword(), salt, 2));
        user.setPasswordSalt(salt);

        user.setCreateTime(new Date());
        user.setModifiedTime(new Date());

        return sysLoginService.register(user);
    }


    /**
     * 登出
     *
     * @return
     */
    @PostMapping(value = "/login", produces = "application/json", params = {"kickout"})
    @ResponseBody
    public Boolean logout() {

        return true;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginForm(Model model) {
        UserDto u = new UserDto();
        model.addAttribute("user", u);
        //model.addAttribute("message", "current page is login");

        return "user/login";
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid @ModelAttribute("user") UserDto user, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return "user/login";
        }

        String username = user.getUsername();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(), user.isRemeberMe());
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
        try {
            //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            log.info("对用户[" + username + "]进行登录验证..验证开始");
            currentUser.login(token);
            log.info("对用户[" + username + "]进行登录验证..验证通过");
        } catch (UnknownAccountException uae) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
            redirectAttributes.addFlashAttribute("message", "未知账户");
        } catch (IncorrectCredentialsException ice) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
            redirectAttributes.addFlashAttribute("message", "密码不正确");
        } catch (LockedAccountException lae) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
            redirectAttributes.addFlashAttribute("message", "账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
            redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多");
        } catch (AuthenticationException ae) {
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            log.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
            ae.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
        }
        //验证是否登录成功
        if (currentUser.isAuthenticated()) {

            log.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
            return "redirect:/index";
        } else {
            token.clear();
            return "redirect:/login";
        }
    }

    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST}, params = {"logout"})
    public String logout(RedirectAttributes redirectAttributes) {
        try {
            SecurityUtils.getSubject().logout();
        } catch (StoppedSessionException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //退出，session被删除
        //redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return "redirect:/login";
    }
}
